//数据库
import usqlite from './usqlite.js'
/**
 * sqlInstance 实例
 *
 */
class sqlInstance {
	/**
	 * 会话表
	 */
	usqlite
	session //会话
	message
	userinfo //user表
	groups //群表
	groupMembers //群成员
	/**
	 * sqlInstance 初始化实例
	 */
	constructor(info) {
		this.usqlite = usqlite
	}
	init(info) {
		console.log(info);
		return new Promise((resolve, reject) => {
			this.usqlite.connect(info, async(err, results) => {
				if (err) {
					console.error('Failed to connect:', err);
				}
				// if (err) {
				// 	console.error('Failed to connect:', err);
				// } else {
				// 	this.establish(info)
				// 	resolve()
				// }
				await this.establish(info)
				
				
				resolve()
			})
		})
	}
	
	close() {
		return new Promise((resolve,reject) => {
		  if(!usqlite)resolve()
		  usqlite.close(result => {
			  if(!result){
				this.usqlite = null
				resolve()
			  }else{
				 reject() 
			  }
		  })
		})
	}
	/**
	 创建表或打开表
	 */
	async establish(info) {
		this.session = this.usqlite.model(
			'session', {
				conversation_id: {
					type: Number,
					index: true,
					comment: '服务器会话id'
				},
				chat_id: {
					primaryKey: true,
					type: String,
					unique: true,
					index: true,
					comment: '当前会话对象的id'
				},
				chat_name: {
					type: String,
					notNull: true,
					comment: '当前会话合并的名字可能是nickname可能是备注名称'
				},
				nick_name: {
					type: String,
					notNull: true,
					comment: '当前会话原名字'
				},
				chat_face: {
					type: String,
					comment: '当前会话的头像'
				},
				chat_member_type: {
					type: String,
					comment: '当前会话的私聊时,用户标识'
				},
				chat_type: {
					type: String,
					notNull: true,
					comment: '当前会话的类型,群聊私聊等private,group '
				},
				last_msg: {
					type: String,
					comment: '当前会话的最后一条消息的内容'
				},
				last_msg_id: {
					type: String,
					comment: '当前会话的最后一条消息的id'
				},
				last_time: {
					type: Number,
					comment: '当前会话的最后一条消息的时间'
				},
				is_top: {
					type: Number,
					comment: '当前会话是否置顶1为置顶'
				},
				tags: {
					type: String,
					comment: '自定义标签'
				},
				tags_font_color: {
					type: String,
					comment: '自定义标签颜色'
				},
				disturbing: {
					type: Number,
					notNull: true,
					default: 0,
					comment: '是否免打扰'
				},
				last_msg_type: {
					type: String,
					comment: '当前会话的最后一条消息的类型'
				},
				at: {
					type: Number,
					comment: '群聊是否被@,1为有人@了我,私聊为0'
				},
				unread_count: {
					type: Number,
					comment: '当前会话的未读数量'
				}
			}
		);

		console.log(this.session);
		//消息
		this.message = this.usqlite.model('messages', {
			id: {
				type: Number,
				primaryKey: true,
				comment: 'id',
				autoIncrement: true
			},
			msg_id: {
				type: String,
				unique: true,
				comment: '消息id',
				index: true
			},
			local_id: {
				type: String,
				unique: true,
				comment: '本地消息id',
				index: true
			},
			conversation_id: {
				type: String,
				comment: '服务器会话id'
			},
			sender_id: {
				type: String,
				notNull: true,
				index: true,
				default: 0,
				comment: '发送者user_id'
			},
			msg_type: {
				type: String,
				notNull: true,
				default: 'text',
				comment: '消息类型'
			},
			content_text: {
				type: String,
				notNull: true,
				comment: '文本内容'
			},
			translate_json: {
				type: String,
				comment: '翻译内容'
			},
			target_id: {
				type: String,
				notNull: true,
				index: true,
				default: 0,
				comment: '发送目标'
			},
			ref_msg_id: {
				type: String,
				notNull: true,
				default: 0,
				comment: '如果该消息是对另一条消息的回复或引用'
			},
			create_time: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '发送时间'
			},
			msg_status: {
				type: String,
				notNull: true,
				index: true,
				default: 'lodding',
				comment: '发送中/发送失败/未读/已读lodding,failed,unread,read'
			},
			ip: {
				type: String,
				comment: 'ip'
			},
			ip_addr: {
				type: String,
				comment: 'ip_addr'
			},
			is_review:{
				type: Number,
				notNull: true,
				default: 1,
				comment: '0审核1不审核2拒绝'
			},
			chat_type: {
				type: String,
				notNull: true,
				default: 'other',
				index: true,
				comment: 'private,group,temp_private,chatroom,other私聊/群聊/临时私聊/聊天室/其他'
			}
		});


		//用户信息
		this.userinfo = this.usqlite.model('userinfo', {
			//用户id
			user_id: {
				type: String,
				primaryKey: true,
				unique: true,
				index: true
			},
			//用户号
			user_no: {
				type: String,
				notNull: true,
				default: 0,
				index: true
			},
			//用户昵称
			nick_name: {
				type: String,
				notNull: true,
			},
			//头像地址
			avatar_url: {
				type: String,
				notNull: true
			},
			//用户类型(0普通用户;1:超管;2:小超管;3:平台管理;4:代理;5:客服;6:无官方头衔账号;7:导师)
			user_type: {
				type: Number,
				notNull: true,
				default: 0
			},
			sex: {
				type: String,
				comment: '性别男,女，保密'
			},
			sign_remark: {
				type: String,
				comment: '个性签名'
			},
			friend_remark: {
				type: String,
				comment: '好友备注'
			},
			disturbing: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '是否免打扰'
			},
			ip: {
				type: String,
				comment: '登录ip'
			},
			friend_group_id:{
				type: String,
				comment: '分组信息id'
			},
			friend_group_name:{
				type: String,
				comment: '分组信息名字'
			}
		});
		//好友
		this.friends = this.usqlite.model('friends', {
			friend_idx: {
				type: String,
				comment: '好友id',
				primaryKey: true,
				unique: true,
				index: true
			},
			friend_group: {
				type: String,
				notNull: true,
				default: 0,
				comment: '好友分组id',
				index: true
			},
			create_time: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '时间'
			},
			update_time: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '更新时间'
			},
		});
		//好友分组
		this.friendGroups = this.usqlite.model('friendGroups', {
			group_id: {
				type: String,
				comment: '分组id',
				primaryKey: true,
				unique: true,
				index: true
			},
			group_name: {
				type: String,
				comment: '分组名称'
			},
			create_time: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '时间'
			},
			update_time: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '更新时间'
			},
		});
		//黑名单
		this.blacks = this.usqlite.model('blacks', {
			black_id: {
				type: String,
				comment: '用户id',
				primaryKey: true,
				unique: true,
				index: true
			},
			create_time: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '时间'
			},
			update_time: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '更新时间'
			},
		});
		//好友申请
		this.friendApp = this.usqlite.model('friendApp', {
			apply_id: {
				type: String,
				index: true,
				comment: '申请id',
				primaryKey: true,
				unique: true,
			},
			friend_id: {
				type: String,
				index: true,
				comment: '用户id',
			},
			isMe: {
				type: String,
				default: '0',
				comment: '是不是我添加的别人0不是我,1是我',
			},
			message: {
				type: String,
				comment: '备注'
			},
			req_status: {
				type: String,
				index: true,
				comment: '请求状态pending,accepted,rejected,ignored'
			},
			create_time: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '时间'
			},
			update_time: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '更新时间'
			},
		});

		//群列表
		this.groups = this.usqlite.model(
			'groups', {
				group_id: {
					primaryKey: true,
					type: String,
					index: true,
					comment: '群组id',
					unique: true,
				},
				mygroup: {
					type: Number,
					notNull: true,
					default: 1,
					comment: '当前用户是否在群内0不在1在,此字段未使用'
				},
				g_no: {
					type: Number,
					notNull: true,
					index: true,
					comment: '群号'
				},
				creator_id: {
					type: Number,
					notNull: true,
					default: 0,
					comment: '创建人'
				},
				avatar_url: {
					type: String,
					notNull: true,
					comment: '群头像'
				},
				group_name: {
					type: String,
					notNull: true,
					comment: '群名称'
				},
				description: {
					type: String,
					comment: '群简介'
				},
				disturbing: {
					type: Number,
					notNull: true,
					default: 0,
					comment: '是否免打扰'
				},
				userRole: {
					type: String,
					default: 'member',
					comment: '我在群内的身份member用户，creator创建者 creator,manager,member'
				},
				userMuted: {
					type: Number,
					default: 0,
					comment: '我在群内是否被禁言，0没禁言 1是禁言了'
				},
				userNickname: {
					type: String,
					comment: '我在群内的昵称'
				},
				notice: {
					type: String,
					comment: '群公告'
				},
				is_muted: {
					type: Number,
					notNull: true,
					comment: '禁言状态(0不禁言,1禁言)'
				},
				is_review: {
					type: Number,
					comment: '是否开启审核(0不;1开启)'
				},
				is_invitation: {
					type: Number,
					comment: '允许邀请(0所有人 1普通用户 2管理员 3都不允许)'
				},
				default_qun: {
					type: Number,
					comment: '默认群 (0 否 1是)'
				},
				is_vip: {
					type: Number,
					comment: '是否是vip群 (0不是;1是)'
				},
				qun_level: {
					type: Number,
					comment: '群等级'
				},
				show_sys_msg: {
					type: Number,
					comment: '展示管理消息范围(0所有人 1普通用户 2管理员 3都不允许)'
				},
				show_member_list: {
					type: Number,
					comment: '是否显示群成员'
				},
				show_online_number: {
					type: Number,
					comment: '可显示在线人数范围(0所有人 1普通用户 2管理员 3都不显示)'
				},
				show_ip: {
					type: Number,
					comment: '显示IP (0所有人 1普通用户 2管理员 3都不允许)'
				},
				show_history: {
					type: Number,
					comment: '查看历史消息范围(0所有人 1普通用户 2管理员 3都不允许)'
				},
				show_qun_number: {
					type: Number,
					comment: '显示群总人数(0所有人 1普通用户 2管理员 3都不允许)'
				},
				can_delete_quit_msg: {
					type: Number,
					comment: '删除退群人消息 (0所有人 1普通用户 2管理员 3都不允许)'
				},
				can_withdraw_self_msg: {
					type: Number,
					comment: '允许撤回自己消息 (0所有人 1普通用户 2管理员 3都不允许)'
				},
				can_withdraw_other_msg: {
					type: Number,
					comment: '允许撤回其他人消息 (0所有人 1普通用户 2管理员 3都不允许)'
				},
				can_send_images: {
					type: Number,
					comment: '允许发送图片 0所有人 1普通用户 2管理员 3都不允许'
				},
				can_send_video: {
					type: Number,
					comment: '允许发送视频 0所有人 1普通用户 2管理员 3都不允许'
				},
				can_send_audio: {
					type: Number,
					comment: '允许发送语音 0所有人 1普通用户 2管理员 3都不允许'
				},
				can_send_card: {
					type: Number,
					comment: '允许发送名片 0所有人 1普通用户 2管理员 3都不允许'
				},
				can_quit_range: {
					type: Number,
					comment: '能够退群的人(0所有人 1普通用户 2管理员 3都不允许)'
				},
				can_add_friends: {
					type: Number,
					comment: '可添加好友的人( 0所有人 1普通用户 2管理员 3都不允许)'
				},
				send_msg_auto_translate: {
					type: Number,
					comment: '可添加好友的人( 0所有人 1普通用户 2管理员 3都不允许)'
				},
				can_edit_msg: {
					type: Number,
					comment: '可编辑消息的人( 0所有人 1普通用户 2管理员 3都不允许)'
				},
				can_send_msg: {
					type: Number,
					comment: '允许发言(0所有人 1普通用户 2管理员 3都不允许)'
				},
				tags: {
					type: String,
					comment: '标签'
				},
				tags_font_color: {
					type: String,
					comment: '标签背景色'
				},
				create_time: {
					type: Number,
					notNull: true,
					default: 0,
					comment: '时间'
				},
				update_time: {
					type: Number,
					notNull: true,
					default: 0,
					comment: '更新时间'
				},
			}
		);
		this.groupMembers = this.usqlite.model('groupmembers', {
			group_id: {
				type: String,
				compositeUnique: true,
				index: true,
				comment: '群id'
			},
			user_id: {
				type: String,
				notNull: true,
				index: true,
				comment: '用户user_id',
				compositeUnique: true,
			},
			role: {
				type: String,
				notNull: true,
				comment: '角色creator,manager,member'
			},
			is_muted: {
				type: Number,
				notNull: true,
				default: 0,
				comment: '禁言状态(0不禁言,1禁言)'
			},
			group_nickname: {
				type: String,
				comment: '群内昵称'
			},
			user_nickname: {
				type: String,
				comment: '昵称'
			},
			avatar_url: {
				type: String,
				comment: '头像'
			},
			user_no: {
				type: String,
				comment: '用户号'
			},
			user_type: {
				type: Number,
				comment: '用户身份',
				default: '0',
			},
		});

		await this.ensureAllTablesCreated([this.session,this.message,this.userinfo,this.friends,this.friendGroups,this.blacks,this.friendApp,this.groups,this.groupMembers])
		
		const currentDbVersion = 6; // 当前最新的数据库版本号
		const savedDbVersion = uni.getStorageSync(info.name+'db_version') || 5; // 读取本地存储的数据库版本号
		console.log('-------------------',uni.getStorageSync(info.name+'db_version'));
		uni.setStorageSync(info.name+'db_version', savedDbVersion);
		
		console.log(savedDbVersion);
		if (savedDbVersion < currentDbVersion) {
			try{
				await this.updateDatabase(savedDbVersion);
			}catch(e){
				console.log(e);
			}
		}
		uni.setStorageSync(info.name+'db_version', currentDbVersion);
	}
	async updateDatabase(oldVersion, newVersion) {
		console.log(oldVersion);
	    if (oldVersion < 2) {
	        // 版本1 -> 版本2，添加群资料添加字段
			try{
				let sql = 'ALTER TABLE groups ADD COLUMN show_member_list numeric'
				await this.groups.executeSql(sql)
			}catch(e){
				// throw e;
				console.log(e);
			}
			
	    }
		if (oldVersion < 3) {
		    // 版本2 -> 版本3，添加群资料添加字段
			try{
				let sql = 'ALTER TABLE groups ADD COLUMN can_edit_msg numeric'
				await this.groups.executeSql(sql)
			}catch(e){
				// throw e;
				console.log(e);
			}
		}
		if (oldVersion < 4) {
		    // 版本3 -> 版本4，添加群资料添加字段
			try{
				let sql = 'ALTER TABLE groups ADD COLUMN tags varchar'
				await this.groups.executeSql(sql)
				let sql1 = 'ALTER TABLE groups ADD COLUMN tags_font_color varchar'
				await this.groups.executeSql(sql1)
				let sql2 = 'ALTER TABLE session ADD COLUMN tags varchar'
				await this.groups.executeSql(sql2)
				let sql3 = 'ALTER TABLE session ADD COLUMN tags_font_color varchar'
				await this.groups.executeSql(sql3)
			}catch(e){
				// throw e;
				console.log(e);
			}
		}
		if (oldVersion < 5) {
		    // 版本2 -> 版本3，添加翻译信息字段
			try{
				let sql = 'ALTER TABLE messages ADD COLUMN translate_json varchar'
				await this.groups.executeSql(sql)
			}catch(e){
				if (!e.message.includes("duplicate column name")) {
					console.log('错误打印',e);  // 打印其他异常
					throw e;  // 重新抛出非重复列异常，停止更新
				}else{
					console.log('已有错误打印,不会抛错',e);
				}
			}
		}
		if (oldVersion < 6) {
			console.log('更新数据库版本6------------------------');
		    // 版本2 -> 版本3，添加群发送翻译字段
			try{
				let sql = 'ALTER TABLE groups ADD COLUMN send_msg_auto_translate varchar'
				await this.groups.executeSql(sql)
			}catch(e){
				if (!e.message.includes("duplicate column name")) {
					console.log('错误打印',e);  // 打印其他异常
					throw e;  // 重新抛出非重复列异常，停止更新
				}else{
					console.log('已有错误打印,不会抛错',e);
				}
			}
		}
		
		
	}

	async ensureAllTablesCreated(models) {
		
		const initPromises = models.map(model => model.init());
		try {
			await Promise.all(initPromises);
			console.log("所有表创建成功");
		} catch (error) {
			console.log(1111);
			console.error("表创建过程中出现问题:", error);
		}
	}
}

export default sqlInstance